package it.unibz.ti2.internetPizzeria.servlets;

import it.unibz.ti2.internetPizzeria.dao.UserDAO;
import it.unibz.ti2.internetPizzeria.entities.User;
import it.unibz.ti2.internetPizzeria.utils.ServletUtil;
import it.unibz.ti2.internetPizzeria.webAttributes.UserInfo;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Authenticating user
 */
public class Login extends HttpServlet{

	private static final long serialVersionUID = -8513599518447086160L;

	protected void doGet(HttpServletRequest arg0, HttpServletResponse arg1) throws ServletException, IOException {
		this.doPost(arg0, arg1);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	
		UserDAO userDAO = new UserDAO();
		userDAO.openSession();
		try {
			String userName = request.getParameter("userName");
			String password = request.getParameter("password");
			if (userName != null && !userName.equals("") && password != null
					&& !password.equals("")) {
				
				User user = userDAO.getUserByLogin(userName);
				if (user != null && user.getPasswordHash() == password.hashCode()) {
					UserInfo userInfo = new UserInfo(user.getId(), user.getClass().getSimpleName());
					request.getSession().setAttribute("userInfo", userInfo);							
					if (userInfo.getUserType().equals("Customer")){
						ServletUtil.redirect(request, response, "/newOrder");
					} else if (userInfo.getUserType().equals("Employee")){
						ServletUtil.redirect(request, response, "/ordersReadyToDeliver");
					} else if (userInfo.getUserType().equals("Manager")) {
						ServletUtil.redirect(request, response, "/manageConfiguration");
					}										
				} else {
					ServletUtil.redirect(request, response, "/login.jsp");					
				}								

			} else {
				ServletUtil.redirect(request, response, "/login.jsp");					
			}
		} catch (Exception ex) {			
			ex.printStackTrace();
		} finally {
			userDAO.closeSession();					
		}
	}

}
